package com.ecode.ecny.flow;

import com.ecode.ecny.chain.ErrorHandler;
import com.ecode.ecny.chain.ProcessNode;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * @ClassName FlowChain
 * @Author mjlft
 * @Date 2021/8/14 16:32
 * @Version 1.0
 * @Description 执行链
 */
@Data
public class FlowChain {
    Logger logger = LoggerFactory.getLogger(FlowChain.class);
    private String name;
    private ProcessNode node;
    private FlowChain next;

    @Value("ecny.show.node.timeout")
    private int nodeTimeOut = 1000;
    @Value("ecny.show.pod.timeout")
    private int podTimeOut = 3000;

    /**
     * 添加下一个任务执行节点
     *
     * @param node
     * @return
     */
    public FlowChain addNext(ProcessNode node, String name) {
        next = new FlowChain();
        next.setNode(node);
        next.setName(name);
        return next;
    }

    /**
     * 初始化任务链
     *
     * @param node
     * @return
     */
    public static FlowChain init(ProcessNode node, String name) {
        FlowChain head = new FlowChain();
        head.setNode(node);
        head.setName(name);
        return head;
    }

    /**
     * 执行流程
     *
     * @param content
     */
    public void doFlow(FlowContent content, ErrorHandler errorHandler) {
        long podStartTime = System.currentTimeMillis();
        try {
            FlowChain flowChain = this;
            while (flowChain.getNode() != null) {
                long startTime = System.currentTimeMillis();
                flowChain.getNode().doExe(content);
                long endTime = System.currentTimeMillis();
                logger.info("【{}】任务{}耗时:{}", content.getSeqNo(), flowChain.getName(), endTime - startTime);
                flowChain = flowChain.getNext();
                if(flowChain == null){
                    break;
                }
            }
        } catch (Exception e) {
            errorHandler.errorHandler(content, e);
        }
        long podEndTime = System.currentTimeMillis();
        logger.info("【{}】任务{}耗时:{}", content.getSeqNo(), podEndTime - podStartTime);
    }
}
